'''
Created on Jan 27, 2013

@author: kafkef
'''


from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, QSettings, QVariant

from dexen.system import client
from dexen.system.client import ui
from dexen.system.common import service
from dexen.system.client.ui.remote.slaves import SlavesInfoWdg
from dexen.system.client.ui.remote.nodes import NodesInfoWdg
from dexen.system.client.ui.remote.jobs import JobsInfoWdg, GetJobsInfoWdg,\
    GetJobListWdg


svr_proxy = client.GetServerProxy()

_svrinfo_tab_wdg = None
_connection_wdg = None

def GetServerInfoTabWdg():
    global _svrinfo_tab_wdg
    if _svrinfo_tab_wdg is None:
        _svrinfo_tab_wdg = ServerInfoTabWdg()
    return _svrinfo_tab_wdg

def GetConnectionWdg():
    global _connection_wdg
    if _connection_wdg is None:
        _connection_wdg = ConnectionWdg()
    return _connection_wdg

class ConnectionWdg(QWidget):
    def __init__(self):
        super(ConnectionWdg, self).__init__()
        self.svr_addrs = []
        self._create_widgets()

    def _create_widgets(self):
        layout = QHBoxLayout()
        
        self.addressLabel = QLabel("Dexen Server Address:")
        self.addrComboBox = QComboBox()
        self.addrComboBox.setEditable(True)
        self.addrComboBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.connectBtn = QPushButton("Connect")
        layout.addWidget(self.addressLabel)
        layout.addWidget(self.addrComboBox)
        layout.addWidget(self.connectBtn)
         
        self.setLayout(layout)

        # Configure signal/slots
        self.connect(self.connectBtn, SIGNAL("clicked()"), 
                     self.on_connectBtn_clicked)
    
    def _add_address(self, addr):
        for i, elem in enumerate(self.svr_addrs):
            if elem == addr:
                del self.svr_addrs[i]
                break
        self.svr_addrs.insert(0, addr)
        if len(self.svr_addrs) > 5:
            assert len(self.svr_addrs) == 6
            del self.svr_addrs[5]
        
        for i in xrange(self.addrComboBox.count()):
            print "item text: ", str(self.addrComboBox.itemText(i))
            if str(self.addrComboBox.itemText(i)) == addr:
                self.addrComboBox.removeItem(i)
                break
        self.addrComboBox.insertItem(0, addr)
        if self.addrComboBox.count() > 5:
            assert self.addrComboBox.count() == 6
            self.addrComboBox.removeItem(5)
        # After inserting the address to the front, change the current index
        self.addrComboBox.setCurrentIndex(0)
    
    def on_connectBtn_clicked(self):
        if str(self.connectBtn.text()) == "Connect":
            ui.GetMainWindow().connect_server(str(self.addrComboBox.currentText()))
        else:
            ui.GetMainWindow().disconnect_server()

    def on_connect(self):
        self._add_address(str(self.addrComboBox.currentText()))
        self.connectBtn.setText("Disconnect")
        self.addrComboBox.setEnabled(False)
    
    def on_disconnect(self):
        self.connectBtn.setText("Connect")
        self.addrComboBox.setEnabled(True)

    def save_settings(self):
        settings = QSettings()
        settings.beginGroup("ConnectionWdg")
        settings.setValue("ServerAddresses", (self.svr_addrs, ))
        settings.endGroup()

    def restore_settings(self):
        settings = QSettings()
        settings.beginGroup("ConnectionWdg")
        self.svr_addrs = settings.value("ServerAddresses", QVariant(([],))).toPyObject()[0]
        settings.endGroup()
        #print "svr address: ", self.svr_addrs
        for addr in self.svr_addrs:
            self.addrComboBox.addItem(addr)
        self._add_address(service.get_my_ip())
        #print "svr address: ", self.svr_addrs
        
        


#===============================================================================
# 
#===============================================================================
class ServerInfoTabWdg(QTabWidget):
    def __init__(self):
        super(ServerInfoTabWdg, self).__init__()
        self._create_widgets()

    def _create_widgets(self):
        self.jobsTab = GetJobsInfoWdg()
        self.nodesTab = NodesInfoWdg()
        self.slavesTab = SlavesInfoWdg()
        self.addTab(self.jobsTab, "Jobs")
        self.addTab(self.nodesTab, "Nodes")
        self.addTab(self.slavesTab, "Slaves")
    
    def refresh(self):
        self.jobsTab.refresh()
    
    def on_connect(self):
        self.jobsTab.on_connect()
        self.nodesTab.on_connect()
        self.slavesTab.on_connect()
    
    def on_disconnect(self):
        self.jobsTab.on_disconnect()
        self.nodesTab.on_disconnect()
        self.slavesTab.on_disconnect()
    
    def save_settings(self):
        self.jobsTab.save_settings()
        self.nodesTab.save_settings()
        self.slavesTab.save_settings()
    
    def restore_settings(self):
        self.jobsTab.restore_settings()
        self.nodesTab.restore_settings()
        self.slavesTab.restore_settings()
        
#===============================================================================
# Container of the above components
#===============================================================================
class RemoteSiteWdg(QWidget):
    def __init__(self):
        super(RemoteSiteWdg, self).__init__()
        self.jobListWdg = GetJobListWdg()
        self._create_widgets()        

    def _create_widgets(self):
        layout = QVBoxLayout()
        self.connectionWdg = GetConnectionWdg()
        self.svrInfoTabWdg = GetServerInfoTabWdg()        
        layout.addWidget(self.connectionWdg)
        layout.addWidget(self.svrInfoTabWdg)
        self.setLayout(layout)

    def on_connect(self):
        self.connectionWdg.on_connect()
        self.svrInfoTabWdg.on_connect()

    def on_disconnect(self):
        self.connectionWdg.on_disconnect()
        self.svrInfoTabWdg.on_disconnect()

    def refresh(self):
        self.svrInfoTabWdg.refresh()
    
    def current_job(self):
        return self.jobListWdg.current_job()

    def save_settings(self):
        self.connectionWdg.save_settings()
        self.svrInfoTabWdg.save_settings()
    
    def restore_settings(self):
        self.connectionWdg.restore_settings()
        self.svrInfoTabWdg.restore_settings()

